package com.xmy.cultivate.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xmy.cultivate.entity.*;
import com.xmy.cultivate.entity.views.EnrollDetail;
import com.xmy.cultivate.entity.views.EnrollGrantDetail;
import com.xmy.cultivate.entity.views.EnrollGrantOperate;
import com.xmy.cultivate.entity.views.EnrollSummary;
import com.xmy.cultivate.excel.ExcelEnrollRecord;
import com.xmy.cultivate.exception.CommonException;
import com.xmy.cultivate.mapper.*;
import com.xmy.cultivate.respons.ResTranscriptScore;
import com.xmy.cultivate.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xmy.cultivate.util.CommonUtil;
import com.xmy.cultivate.util.ResultCode;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * <p>
 * 招生数据 服务实现类
 * </p>
 *
 * @author min
 * @since 2023-02-10
 */
@Service
public class EnrollInfoServiceImpl extends ServiceImpl<EnrollInfoMapper, EnrollInfo> implements IEnrollInfoService {

    @Autowired
    EnrollInfoMapper enrollInfoMapper;

    @Autowired
    StaffMapper staffMapper;

    @Autowired
    @Lazy
    OrderApplyMapper orderApplyMapper;

    @Autowired
    @Lazy
    OrderDetailMapper orderDetailMapper;

    @Autowired
    @Lazy
    IEnrollTeamMemberService iEnrollTeamMemberService;

    @Autowired
    StudentMapper studentMapper;

    @Autowired
    @Lazy
    SubjectsMapper subjectsMapper;

    @Autowired
    @Lazy
    OrganizationMapper organizationMapper;

    @Autowired
    @Lazy
    StudentGradeMapper studentGradeMapper;

    @Autowired
    DictMapper dictMapper;

    @Autowired
    GradeMapper gradeMapper;

    @Autowired
    IQuarterService iQuarterService;

    @Autowired
    IRecordCourseService iRecordCourseService;

    @Autowired
    ITranscriptService iTranscriptService;

    @Autowired
    IEnrollSetService iEnrollSetService;

    @Autowired
    IMqPushService iMqPushService;

    @Autowired
    IEnrollInfoGrantSchoolService iEnrollInfoGrantSchoolService;


    public List<EnrollInfo> getEnrollInfoList(String orderId){
        QueryWrapper<EnrollInfo> enrollInfoQueryWrapper = new QueryWrapper<>();
        enrollInfoQueryWrapper.eq("order_id",orderId);
        enrollInfoQueryWrapper.orderByAsc("type");
        List<EnrollInfo> enrollInfoList = enrollInfoMapper.selectList(enrollInfoQueryWrapper);

        for (EnrollInfo enrollInfo:enrollInfoList){
            Staff staff = staffMapper.selectById(enrollInfo.getTeacherId());
            if(staff != null){
                enrollInfo.setTeacherName(staff.getName());
            }
        }
        return enrollInfoList;
    }

    public boolean addEnrollInfo(OrderApply orderApplyInfo){

        OrderApply orderApply = orderApplyMapper.selectById(orderApplyInfo.getId());
        if(orderApply == null){
            throw new CommonException(ResultCode.NOORDER);
        }
        OrderDetail orderDetail = orderDetailMapper.selectOne(new QueryWrapper<OrderDetail>().eq("order_id",orderApply.getId()).last("limit 1"));

        EnrollSet enrollSet = iEnrollSetService.findEnrollSetForDate(orderApply.getSchoolId());


        BigDecimal inviteMoney = enrollSet.getPushMoney1();
        BigDecimal auditionMoney = enrollSet.getPushMoney2();
        BigDecimal bargainMoney = enrollSet.getPushMoney3();
        LocalDate localDate = LocalDate.now();

        //邀约:1
        if(orderApplyInfo.getInviteList()!=null){
            Integer inviteCount = orderApplyInfo.getInviteList().size();
            if(inviteCount>0){
                Long inviteCountAt = this.getEnrollInfoCount(orderApply.getId(),1);

                Double dealNum = 1.0/inviteCount;
                Integer i = 0;
                Integer type = 1;
                for (Long id:orderApplyInfo.getInviteList()){
                    if((i+inviteCountAt)<2){
                        Long teamId =  iEnrollTeamMemberService.getTeamIdForteacherId(id);
                        addEnrollInfoType(id,teamId,orderDetail.getSubjectsId(),orderApply.getStudentId(),orderApply.getId(),orderApply.getSchoolId(),dealNum,inviteMoney,inviteCount,orderApply.getHandleDate(),type);
                    }
                    i++;
                }
                this.updateEnrollDeal(orderApply.getId(),1);
            }
        }

        if(orderApplyInfo.getAuditionList() !=null){
            //试听:2
            Integer auditionCount = orderApplyInfo.getAuditionList().size();
            if(auditionCount>0){
                Long auditionCountAt = this.getEnrollInfoCount(orderApply.getId(),2);
                Double dealNum = 1.0/auditionCount;
                Integer i = 0;
                Integer type = 2;
                for (Long id:orderApplyInfo.getAuditionList()){
                    if((i+auditionCountAt)<2){
                        Long teamId =  iEnrollTeamMemberService.getTeamIdForteacherId(id);
                        addEnrollInfoType(id,teamId,orderDetail.getSubjectsId(),orderApply.getStudentId(),orderApply.getId(),orderApply.getSchoolId(),dealNum,auditionMoney,auditionCount,orderApply.getHandleDate(),type);
                    }
                    i++;
                }
                this.updateEnrollDeal(orderApply.getId(),2);
            }
        }

        if(orderApplyInfo.getBargainList()!=null){
            //成交:3
            Integer bargainCount = orderApplyInfo.getBargainList().size();
            if(bargainCount>0){
                Long bargainCountAt = this.getEnrollInfoCount(orderApply.getId(),3);
                Double dealNum = 1.0/bargainCount;
                Integer i = 0;
                Integer type = 3;
                for (Long id:orderApplyInfo.getBargainList()){
                    if((i+bargainCountAt)<2){
                        Long teamId =  iEnrollTeamMemberService.getTeamIdForteacherId(id);
                        addEnrollInfoType(id,teamId,orderDetail.getSubjectsId(),orderApply.getStudentId(),orderApply.getId(),orderApply.getSchoolId(),dealNum,bargainMoney,bargainCount,orderApply.getHandleDate(),type);
                    }
                    i++;
                }
                this.updateEnrollDeal(orderApply.getId(),3);
            }
        }

        if(orderApplyInfo.getPhoneInviteList()!=null){
            //号码:4
            Integer phoneCount = orderApplyInfo.getPhoneInviteList().size();
            if(phoneCount >0){
                Long phoneCountAt = this.getEnrollInfoCount(orderApply.getId(),4);
                Double dealNum = 1.0/ phoneCount;
                Integer i = 0;
                Integer type = 4;
                for (Long id:orderApplyInfo.getPhoneInviteList()){
                    if((i+phoneCountAt)<2){
                        Long teamId =  iEnrollTeamMemberService.getTeamIdForteacherId(id);
                        addEnrollInfoType(id,teamId,orderDetail.getSubjectsId(),orderApply.getStudentId(),orderApply.getId(),orderApply.getSchoolId(),dealNum,bargainMoney, phoneCount,orderApply.getHandleDate(),type);
                    }
                    i++;
                }
                this.updateEnrollDeal(orderApply.getId(),4);
            }
        }

        try {
            // 添加数据到enroll_info_grant_school表
            QueryWrapper wrapper = new QueryWrapper<>();
            wrapper.eq("order_id", orderApply.getId());
            wrapper.last("limit 1");
            EnrollInfoGrantSchool enrollInfoGrantSchool = iEnrollInfoGrantSchoolService.getOne(wrapper);
            if (enrollInfoGrantSchool == null) {
                EnrollInfoGrantSchool grantSchool = new EnrollInfoGrantSchool();
                grantSchool.setOrderId(orderApply.getId());
                grantSchool.setSchoolId(orderApply.getSchoolId());
                grantSchool.setSubjectsId(orderDetail.getSubjectsId());
                grantSchool.setStudentId(orderApply.getStudentId());
                grantSchool.setGrantNum(BigDecimal.valueOf(1.0));
                iEnrollInfoGrantSchoolService.save(grantSchool);
            } else {
//            enrollInfoGrantSchool.setSchoolId(orderApply.getSchoolId());
//            enrollInfoGrantSchool.setSubjectsId(orderDetail.getSubjectsId());
//            enrollInfoGrantSchool.setStudentId(orderApply.getStudentId());
//            enrollInfoGrantSchool.setGrantNum(BigDecimal.valueOf(1.0));
//            iEnrollInfoGrantSchoolService.updateById(enrollInfoGrantSchool);
            }
        }catch (Exception ex){

        }

        return true;
    }

    /**
     * 按类型添加
     * @param teacherId
     * @param teamId
     * @param subjectsId
     * @param studentId
     * @param orderId
     * @param schoolId
     * @param dealNum
     * @param inviteMoney
     * @param count
     * @param handleDate
     * @param type
     * @return
     */
    private boolean addEnrollInfoType(Long teacherId,Long teamId,Long subjectsId,Long studentId,Long orderId,Long schoolId,Double dealNum,BigDecimal inviteMoney,Integer count,LocalDate handleDate,Integer type){
        EnrollInfo enrollInfo = new EnrollInfo();
        enrollInfo.setTeacherId(teacherId);
        enrollInfo.setSubjectsId(subjectsId);
        enrollInfo.setStudentId(studentId);
        enrollInfo.setTeamId(teamId);
        enrollInfo.setOrderId(orderId);
        enrollInfo.setSchoolId(schoolId);
        enrollInfo.setDealNum(dealNum);
        enrollInfo.setPushMoney(inviteMoney.divide(new BigDecimal(count),2,BigDecimal.ROUND_HALF_UP));
        enrollInfo.setAddDate(handleDate);//与订单经办日期同步
        enrollInfo.setType(type);
        enrollInfoMapper.insert(enrollInfo);
        return true;
    }

    /**
     * 修改数量与提成
     * @param orderId
     * @param type
     * @return
     */
    private boolean updateEnrollDeal(Long orderId,Integer type){

        OrderApply orderApply = orderApplyMapper.selectById(orderId);

        EnrollSet enrollSet = iEnrollSetService.findEnrollSetForDate(orderApply.getSchoolId());

        BigDecimal inviteMoney = enrollSet.getPushMoney1();
        BigDecimal auditionMoney = enrollSet.getPushMoney2();
        BigDecimal bargainMoney = enrollSet.getPushMoney3();
        BigDecimal phoneMoney = enrollSet.getPushMoney4();

        BigDecimal pushMonnyBase;
        if(type.equals(1)){
            pushMonnyBase = inviteMoney;
        }else if (type.equals(2) || type.equals(3)){
            pushMonnyBase = auditionMoney;
        }else {
            pushMonnyBase = phoneMoney;
        }

        List<EnrollInfo> enrollInfoList = this.getEnrollInfoList(orderId,type);
        Double dealNum = 1.0/enrollInfoList.size();
        BigDecimal pushMonny;
        for (EnrollInfo enrollInfo:enrollInfoList){
            enrollInfo.setDealNum(dealNum);
            pushMonny = pushMonnyBase.multiply(new BigDecimal(dealNum));
            enrollInfo.setPushMoney(pushMonny);
            enrollInfoMapper.updateById(enrollInfo);
        }
        return true;
    }

    private Long getEnrollInfoCount(Long orderId,Integer type){
        QueryWrapper<EnrollInfo> enrollInfoQueryWrapper = new QueryWrapper<>();
        enrollInfoQueryWrapper.eq("order_id",orderId);
        enrollInfoQueryWrapper.eq("type",type);
        return enrollInfoMapper.selectCount(enrollInfoQueryWrapper);
    }

    private List<EnrollInfo> getEnrollInfoList(Long orderId,Integer type){
        QueryWrapper<EnrollInfo> enrollInfoQueryWrapper = new QueryWrapper<>();
        enrollInfoQueryWrapper.eq("order_id",orderId);
        enrollInfoQueryWrapper.eq("type",type);
        return enrollInfoMapper.selectList(enrollInfoQueryWrapper);
    }

    /**
     * 删除
     * @param id
     * @return
     */
    public boolean delEnrollInfo(String id){
        EnrollInfo enrollInfo = enrollInfoMapper.selectById(id);
        if(enrollInfo!=null){
            enrollInfoMapper.deleteById(enrollInfo.getId());
            this.updateEnrollDeal(enrollInfo.getOrderId(),enrollInfo.getType());
            /*
            List<EnrollInfo> enrollInfoList = this.getEnrollInfoList(enrollInfo.getOrderId(),enrollInfo.getType());
            Double dealNum = 1.0/enrollInfoList.size();
            for (EnrollInfo enrollInfoUpdate:enrollInfoList){
                enrollInfoUpdate.setDealNum(dealNum);
                enrollInfoMapper.updateById(enrollInfoUpdate);
            }*/
        }
        return true;
    }

    @Override
    public EnrollInfo getGrantCount(Long orderId){
        return  enrollInfoMapper.getGrantCount(orderId);
    }

    public IPage<EnrollDetail> getParticulars(IPage<?> page, Wrapper wrapper){

        QueryWrapper<EnrollInfo> enrollInfoQueryWrapper = new QueryWrapper<>();

        List<EnrollDetail> enrollDetailList = new ArrayList<>();
        IPage<EnrollDetail> iPage = enrollInfoMapper.getParticulars(page,wrapper);

        for (EnrollDetail enrollDetail:iPage.getRecords()){

            Student student = studentMapper.selectById(enrollDetail.getStudentId());
            if (student != null){
                enrollDetail.setStudentName(student.getName());
            }
            Subjects subjects = subjectsMapper.selectById(enrollDetail.getSubjectsId());
            if(subjects!=null){
                enrollDetail.setSubjectsName(subjects.getName());
            }

            if (enrollDetail.getYearClassId()!=null){
                enrollDetail.setYearClassName(CommonUtil.getYearClassNameForId(enrollDetail.getYearClassId()));
            }
            Organization organization = organizationMapper.selectById(enrollDetail.getSchoolId());
            if (organization!=null){
                enrollDetail.setSchoolName(organization.getName());
            }
            OrderApply orderApply = orderApplyMapper.selectById(enrollDetail.getOrderId());
            if (orderApply!=null){
                QueryWrapper<OrderDetail> orderDetailQueryWrapper = new QueryWrapper<>();
                orderDetailQueryWrapper.eq("order_id",orderApply.getId());
                orderDetailQueryWrapper.last("limit 1");
                OrderDetail orderDetail = orderDetailMapper.selectOne(orderDetailQueryWrapper);
                if (orderDetail != null){
                    Grade grade = gradeMapper.selectById(orderDetail.getGradeId());
                    if (grade!=null){
                        QueryWrapper<Dict> dictQueryWrapper = new QueryWrapper<>();
                        dictQueryWrapper.eq("num",grade.getYearClassId());
                        dictQueryWrapper.eq("type",14);
                        dictQueryWrapper.last("limit 1");
                        Dict dict = dictMapper.selectOne(dictQueryWrapper);
                        if (dict!=null){
                            enrollDetail.setYearClassName(dict.getName());
                        }
                    }
                }
            }

            /**
             * 邀约人
             */
            List<String> phoneNameList = this.getEnrollTeacher(enrollDetail.getOrderId(),4);

            /**
             * 邀约人
             */
            List<String> inviteNameList = this.getEnrollTeacher(enrollDetail.getOrderId(),1);
            /**
             * 试听人
             */
            List<String> auditionNameList = this.getEnrollTeacher(enrollDetail.getOrderId(),2);
            /**
             * 成交人
             */
            List<String> bargainNameList = this.getEnrollTeacher(enrollDetail.getOrderId(),3);

            enrollDetail.setPhoneNames(String.join(",",phoneNameList));
            enrollDetail.setInviteNames(String.join(",",inviteNameList));
            enrollDetail.setAuditionNames(String.join(",",auditionNameList));
            enrollDetail.setBargainNames(String.join(",",bargainNameList));

            if (enrollDetail.getNotCheckType()>0){
                enrollDetail.setCheckType(0);
            }else {
                enrollDetail.setCheckType(1);
            }
        }

        return iPage;
    }


    @Override
    public IPage<EnrollGrantDetail> getParticularsGrantDetail(IPage<?> page, Wrapper wrapper){
        return enrollInfoMapper.getParticularsGrantDetail(page,wrapper);
    }

    @Override
    public List<String> getEnrollTeacher(Long orderId,Integer type) {

        QueryWrapper<EnrollInfo> enrollInfoQueryWrapper = new QueryWrapper<>();
        enrollInfoQueryWrapper.eq("order_id",orderId);
        //enrollInfoQueryWrapper.eq("order_id",incomeDayReport.getOrderId());

        List<String> teacherList = new ArrayList<>();

        List<EnrollInfo> enrollInfoList = enrollInfoMapper.selectList(enrollInfoQueryWrapper);
        for (EnrollInfo enrollInfo:enrollInfoList){
            if (enrollInfo.getType().equals(type)){
                Staff staff = staffMapper.selectById(enrollInfo.getTeacherId());
                if (staff!=null){
                    teacherList.add(staff.getName());
                }
            }
        }
        return teacherList;
    }

    public IPage<EnrollRecord> getEnrollStudent(IPage<?> page,Wrapper wrapper){
        IPage<EnrollRecord> iPage = enrollInfoMapper.getEnrollStudent(page,wrapper);
        return iPage;
    }

    public List<ExcelEnrollRecord> getExcelEnrollStudent( Wrapper wrapper){
        List<ExcelEnrollRecord> excelEnrollRecordIPage = enrollInfoMapper.getExcelEnrollStudent(wrapper);
        return excelEnrollRecordIPage;
    }

    public List<EnrollInfo> getListByTeacher(Wrapper wrapper){
        List<EnrollInfo> enrollInfoList = enrollInfoMapper.getListByTeacher(wrapper);
        return enrollInfoList;
    }


    /**
     * 上过两次课的更改为真真实数据
     * @return
     */
    @Override
    public boolean updateIsTrue(Quarter quarterNow){
        QueryWrapper<EnrollInfo> enrollInfoQueryWrapper = new QueryWrapper<>();
        enrollInfoQueryWrapper.eq("year_part",quarterNow.getYearPart());
        enrollInfoQueryWrapper.eq("quarter_num",quarterNow.getNum());
        enrollInfoQueryWrapper.eq("is_true",0);
        enrollInfoQueryWrapper.eq("is_return",0);
        List<EnrollInfo> enrollInfoList = enrollInfoMapper.getEnrollInfoList(enrollInfoQueryWrapper);
        for (EnrollInfo enrollInfo:enrollInfoList){
            Integer count = iRecordCourseService.getRecordCountArrive(quarterNow.getYearPart(),quarterNow.getNum(),enrollInfo.getStudentId(),enrollInfo.getSubjectsId());
            if (count>=2){
                enrollInfo.setIsTrue(1);
                this.updateById(enrollInfo);
            }
        }
        return true;
    }

    @Override
    public IPage<EnrollSummary> getParticularsDataSummary(IPage<?> page, Wrapper wrapper){

        IPage<EnrollSummary> iPage = enrollInfoMapper.getParticularsDataSummary(page,wrapper);

        for (EnrollSummary enrollDetail:iPage.getRecords()){
            Organization organization = organizationMapper.selectById(enrollDetail.getSchoolId());
            if (organization!=null){
                enrollDetail.setSchoolName(organization.getName());
            }

            Staff staff = staffMapper.selectById(enrollDetail.getTeacherId());
            if (staff != null) {
                enrollDetail.setTeacherName(staff.getName());
            }
        }

        return iPage;
    }

    private String convertToLocalDateTime(long timestampMillis) {
        // 将13位时间戳转换为秒
        long timestampSeconds = timestampMillis / 1000;
        // 使用Instant类转换为LocalDateTime
        Instant instant = Instant.ofEpochSecond(timestampSeconds);
        LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        return localDateTime.format(formatter);
    }

    @Override
    public IPage<EnrollGrantOperate> getParticularsGrant(IPage<?> page, Wrapper wrapper, Integer showType){

        IPage<EnrollGrantOperate> iPage = enrollInfoMapper.getParticularsGrant(page,wrapper);

        //按学生查看
        if (showType.equals(2)){
            for (EnrollGrantOperate enrollGrantOperate:iPage.getRecords()){

                List<String> phoneList = new ArrayList<>();//号码

                List<String> invitationList = new ArrayList<>();//邀约

                List<String> trialListeningList = new ArrayList<>();//试听

                List<String> transactionList = new ArrayList<>();//成交
                if (StringUtils.isNotBlank(enrollGrantOperate.getEnrollTeacherStr())){
                    List<String> teacherList = Arrays.asList(enrollGrantOperate.getEnrollTeacherStr().split(","));
                    List<String> typeList = Arrays.asList(enrollGrantOperate.getEnrollTypeStr().split(","));
                    if (teacherList.size() == typeList.size()){
                        Integer i =0;
                        for (String type:typeList){
                            if (type.equals("1")){
                                invitationList.add(teacherList.get(i));
                            }else if (type.equals("2")){
                                trialListeningList.add(teacherList.get(i));
                            }else if (type.equals("3")){
                                transactionList.add(teacherList.get(i));
                            }else if (type.equals("4")){
                                phoneList.add(teacherList.get(i));
                            }
                            i++;
                        }
                    }
                }

                enrollGrantOperate.setPhoneNames(String.join(",",phoneList));
                enrollGrantOperate.setInviteNames(String.join(",",invitationList));
                enrollGrantOperate.setAuditionNames(String.join(",",trialListeningList));
                enrollGrantOperate.setBargainNames(String.join(",",transactionList));

            /*Organization organization = organizationMapper.selectById(enrollDetail.getSchoolId());
            if (organization!=null){
                enrollDetail.setSchoolName(organization.getName());
            }

            Staff staff = staffMapper.selectById(enrollDetail.getTeacherId());
            if (staff != null) {
                enrollDetail.setTeacherName(staff.getName());
            }

            if (enrollDetail.getIsGrant() == 1) {
                enrollDetail.setOperateTime(convertToLocalDateTime(enrollDetail.getGrantTime()));
            }*/
            }
        }

        return iPage;
    }

    @Override
    @Async("onlineAsync")
    public void addEnrollStudentTranscript(Integer yearPart, Integer quarterNum, Long studentId){

        Integer pageSize =10;
        IPage<OrderDetail> iPage = new Page<>(1,pageSize);

        QueryWrapper<OrderDetail> orderDetailQueryWrapper = new QueryWrapper<>();
        orderDetailQueryWrapper.eq("year_part",yearPart);
        orderDetailQueryWrapper.eq("quarter_num",quarterNum);
        orderDetailQueryWrapper.eq("lesson_type",1);
        //orderDetailQueryWrapper.eq("subjects_id",3);
        if (studentId != null){
            orderDetailQueryWrapper.eq("student_id",studentId);
        }
        orderDetailQueryWrapper.groupBy("student_id","subjects_id");

        orderDetailMapper.selectPage(iPage,orderDetailQueryWrapper);
        Long allPage = iPage.getPages();
        for (Integer i=1;i<=allPage;i++){
            if (!i.equals(1)){
                //continue;
                iPage = new Page<>(i,pageSize);
                orderDetailMapper.selectPage(iPage,orderDetailQueryWrapper);
            }
            for (OrderDetail orderDetail:iPage.getRecords()){
                ChaStudyPlan chaStudyPlan = new ChaStudyPlan();
                chaStudyPlan.setYearPart(yearPart);
                chaStudyPlan.setQuarterNum(quarterNum);
                chaStudyPlan.setStudentId(orderDetail.getStudentId());
                chaStudyPlan.setSubjectsId(orderDetail.getSubjectsId());
                iMqPushService.chaStudyPlanAccuracy(chaStudyPlan);
            }
        }

        /*Quarter quarter = iQuarterService.getQuarterForYearAndNum(yearPart,quarterNum);
        //获取上一个学期
        Quarter lastQuarter = iQuarterService.getLastQuarter(quarter.getYearPart(), quarter.getNum());
        if (lastQuarter.getType().equals(2)) {
            //如果上一学期为假期，再获取上一学期
            lastQuarter = iQuarterService.getLastQuarter(lastQuarter.getYearPart(), lastQuarter.getNum());
        }
        List<EnrollInfo> enrollInfoList = enrollInfoMapper.getEnrollStudentList(yearPart,quarterNum);
        for (EnrollInfo enrollInfo:enrollInfoList){
            this.addDataTranscript(quarter,lastQuarter,enrollInfo.getStudentId(),enrollInfo.getSubjectsId());
        }*/
    }

    @Override
    public boolean addDataTranscript(Quarter quarter, Quarter lastQuarter, Long studentId, Long subjectsId){
        ResTranscriptScore resTranscriptScore = new ResTranscriptScore();
        QueryWrapper<Transcript> transcriptQueryWrapper = new QueryWrapper<>();
        transcriptQueryWrapper.eq("year_part",quarter.getYearPart());
        transcriptQueryWrapper.eq("quarter_num",quarter.getNum());
        transcriptQueryWrapper.eq("exam_num",1);
        transcriptQueryWrapper.eq("student_id",studentId);
        transcriptQueryWrapper.eq("subjects_id",subjectsId);
        transcriptQueryWrapper.eq("is_statistics",1);
        transcriptQueryWrapper.last("limit 1");
        Transcript transcriptOne = iTranscriptService.getOne(transcriptQueryWrapper);
        resTranscriptScore.setExamNum(1);
        if (transcriptOne == null){
            transcriptQueryWrapper.clear();
            transcriptQueryWrapper.eq("year_part",lastQuarter.getYearPart());
            transcriptQueryWrapper.eq("quarter_num",lastQuarter.getNum());
            transcriptQueryWrapper.eq("exam_num",3);//上个学期期末
            transcriptQueryWrapper.eq("student_id",studentId);
            transcriptQueryWrapper.eq("subjects_id",subjectsId);
            transcriptQueryWrapper.eq("is_statistics",1);
            transcriptQueryWrapper.last("limit 1");
            transcriptOne = iTranscriptService.getOne(transcriptQueryWrapper);
            resTranscriptScore.setExamNum(3);
        }
        if (transcriptOne!=null){
            Student student = studentMapper.selectById(studentId);
            resTranscriptScore.setScore(transcriptOne.getScore());
            resTranscriptScore.setScoreType(transcriptOne.getScoreType());
            resTranscriptScore.setSubjectsId(transcriptOne.getSubjectsId());
            iTranscriptService.addStudentClassType(student,quarter,resTranscriptScore,student.getYearClassId());
        }
        return true;
    }

    @Override
    public EnrollInfo getMinAndMaxDate(Long teamId, String startDate, String endDate){
        return enrollInfoMapper.getMinAndMaxDate(teamId,startDate,endDate);
    }

    @Override
    public BigDecimal getParticularsTotal(Long schoolId,
                                          Long teacherId,
                                          String startDate,
                                          String endDate,
                                          String startTrueDate,
                                          String endTrueDate){
        return enrollInfoMapper.getParticularsTotal(schoolId,teacherId,startDate,endDate,startTrueDate,endTrueDate);
    }

    @Override
    public Integer particulartsUpdate(Long schoolId,
                                      Long teacherId,
                                      String startDate,
                                      String endDate,
                                      String grantDate,
                                      Long grantTime,
                                      Long operateTeacherId,
                                      String operateTeacherName,
                                      String startTrueDate,
                                      String endTrueDate,
                                      Long grantNo
    ){
        return enrollInfoMapper.particulartsUpdate(schoolId,teacherId,startDate,endDate,grantDate,grantTime,operateTeacherId,operateTeacherName,startTrueDate,endTrueDate,grantNo);
    }
}
